#python3 prometheus operator告警转接企业微信机器人
from flask import Flask, request, jsonify
import requests
import json

app = Flask(__name__)

# 定义一个接收 POST 请求并转发的路由
@app.route('/forward', methods=['POST'])
def forward_request():
    # 获取原始请求的 JSON 数据
    original_data = request.json

    # 修改数据，这里只是简单地在原始数据中添加一个新的字段
    modified_data = original_data.copy()

    print(modified_data)

    status_ = modified_data['status']
    for alerts_one in modified_data['alerts']:
        severity_ = alerts_one['labels'].get("severity") or ""
        summarycn_ = alerts_one['annotations'].get("summaryCn") or "详情"
        summary_ = alerts_one['annotations'].get("summary") or ""
        # message_ = alerts_one['annotations'].get("message") or ""
        alertname_ = alerts_one['labels'].get("alertname") or ""
        startsat_ = alerts_one.get("startsAt") or ""
        description_ = alerts_one['annotations'].get("description") or ""


        # 构建转发的目标 URL
        target_url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=aaaa'  # 替换为实际的目标 URL

        temp_data = {
            "msgtype":"template_card",
            "template_card":{
                "card_type":"text_notice",
                "source":{
                    "icon_url":"http://xn.prd.sumztech.com:65179/favicon.ico",
                    "desc": alertname_,
                    "desc_color":0
                },
                "main_title":{
                    "title": status_,
                    "desc": summary_
                },
                "emphasis_content":{
                    "title": severity_,
                    "desc": "告警级别"
                },
                "quote_area":{
                    "type":1,
                    "url":"http://192.168.3.189:30880/",
                    "appid":"APPID",
                    "pagepath":"PAGEPATH",
                    "title": summarycn_,
                    "quote_text": startsat_
                },
                "sub_title_text": description_,
                "card_action":{
                    "type":1,
                    "url":"http://192.168.3.189:30880/",
                    "appid":"APPID",
                    "pagepath":"PAGEPATH"
                }
            }
        }

        print(temp_data)
        data = json.dumps(temp_data)
        # 发起转发请求
        header = {
            "Content-Type": "application/json",
            "Charset": "UTF-8"
            }
        response = requests.post(url=target_url, data=data, headers=header)

        print(response.json())

        # 返回转发请求的响应内容
        return jsonify(response.json())

if __name__ == '__main__':
    app.run(host="0.0.0.0", debug=True, port=80)  # 设置启动端口

